import 'dart:async';

import 'package:app_plugin/app_plugin.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';

import 'home.dart';
import 'settings.dart';
import 'webview.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  PageController _pageController = PageController();
  int _currentIndex = 0;
  AppOptions _options;
  Timer _timeDilationTimer;

  @override
  void initState() {
    super.initState();
    _options = AppOptions(
      theme: darkTheme,
      textScaleFactor: kAllTextScaleValues[0],
      timeDilation: timeDilation,
      platform: defaultTargetPlatform,
    );
  }

  @override
  void dispose() {
    _timeDilationTimer?.cancel();
    _timeDilationTimer = null;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: _options.theme.data.copyWith(platform: _options.platform),
      color: Colors.grey,
      showPerformanceOverlay: _options.showPerformanceOverlay,
      checkerboardOffscreenLayers: _options.showOffscreenLayersCheckerboard,
      checkerboardRasterCacheImages: _options.showRasterCacheImagesCheckerboard,
      builder: (BuildContext context, Widget child) {
        return Directionality(
          textDirection: _options.textDirection,
          child: _applyTextScaleFactor(child),
        );
      },
      home: Scaffold(
        body: Container(
          child: PageView(
            children: <Widget>[
              HomePage(),
              WebViewPage(),
              SettingsPage(
                _options,
                _handleOptionsChanged,
              ),
            ],
            physics: NeverScrollableScrollPhysics(),
            controller: _pageController,
            onPageChanged: (index) {
              setState(() {
                _currentIndex = index;
              });
            },
          ),
        ),
        bottomNavigationBar: BottomNavigationBar(
          items: [
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              title: Text('Home'),
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.album),
              title: Text('WebView'),
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.settings),
              title: Text('Settings'),
            ),
          ],
          onTap: (index) {
            _currentIndex = index;
            _pageController.jumpToPage(index);
          },
          currentIndex: _currentIndex,
        ),
      ),
    );
  }

  void _handleOptionsChanged(AppOptions newOptions) {
    setState(() {
      if (_options.timeDilation != newOptions.timeDilation) {
        _timeDilationTimer?.cancel();
        _timeDilationTimer = null;
        if (newOptions.timeDilation > 1.0) {
          // We delay the time dilation change long enough that the user can see
          // that UI has started reacting and then we slam on the brakes so that
          // they see that the time is in fact now dilated.
          _timeDilationTimer = Timer(const Duration(milliseconds: 150), () {
            timeDilation = newOptions.timeDilation;
          });
        } else {
          timeDilation = newOptions.timeDilation;
        }
      }

      _options = newOptions;
    });
  }

  Widget _applyTextScaleFactor(Widget child) {
    return Builder(
      builder: (BuildContext context) {
        return MediaQuery(
          data: MediaQuery.of(context).copyWith(
            textScaleFactor: _options.textScaleFactor.scale,
          ),
          child: child,
        );
      },
    );
  }
}
